package com.yoj.judgeservice.config;

import com.yoj.common.constant.MqConstant;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 判题服务的消息队列配置
 */
@Configuration
public class RabbitMqConfig {

    // 定义交换机
    private final String JUDGE_EXCHANGE_NAME = MqConstant.JUDGE_EXCHANGE_NAME;

    // 定义判题队列
    private final String JUDGE_QUEUE_NAME = MqConstant.JUDGE_QUEUE_NAME;

    // 死信交换机
    private final String JUDGE_DLX_EXCHANGE = MqConstant.JUDGE_DLX_EXCHANGE;

    // 定义死信队列
    private final String JUDGE_DLX_QUEUE_NAME = MqConstant.JUDGE_DLX_QUEUE_NAME;

    // 定义判题队列路由 key
    public static final String JUDGE_ROUTING_KEY = MqConstant.JUDGE_ROUTING_KEY;

    public static final String JUDGE_DLX_ROUTING_KEY = MqConstant.JUDGE_DLX_ROUTING_KEY;

    /**
     * 创建判题交换机
     */
    @Bean
    DirectExchange judgeDirectExchange() {
        return ExchangeBuilder.directExchange(JUDGE_EXCHANGE_NAME).build();
    }

    /**
     * 创建死信交换机
     */
    @Bean
    DirectExchange judgeDlxExchange() {
        return ExchangeBuilder.directExchange(JUDGE_DLX_EXCHANGE).build();
    }

    /**
     * 创建判题队列，绑定死信队列和交换机
     */
    @Bean
    public Queue judgeQueue() {
        return QueueBuilder.durable(JUDGE_QUEUE_NAME)
                .deadLetterExchange(JUDGE_DLX_EXCHANGE)
                .deadLetterRoutingKey(JUDGE_DLX_ROUTING_KEY)
                .build();
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue judgeDlxQueue() {
        return QueueBuilder.durable(JUDGE_DLX_QUEUE_NAME).build();
    }

    /**
     * 绑定判题队列和交换机
     */
    @Bean
    public Binding bindingDirectJudge(Queue judgeQueue, DirectExchange judgeDirectExchange) {
        return BindingBuilder.bind(judgeQueue).to(judgeDirectExchange).with(JUDGE_ROUTING_KEY);
    }

    /**
     * 绑定死信队列和死信交换机
     */
    @Bean
    public Binding bindingDlxJudge(Queue judgeDlxQueue, DirectExchange judgeDlxExchange) {
        return BindingBuilder.bind(judgeDlxQueue).to(judgeDlxExchange).with(JUDGE_DLX_ROUTING_KEY);
    }
}
